from django.shortcuts import render

# Create your views here.

from rest_framework.viewsets import GenericViewSet  # 可以映射路由，以及操作数据库
from rest_framework.mixins import ListModelMixin  # 只是get请求得到数据
from rest_framework.response import Response
from home import models
from home import serializers
from django.conf import settings
from django.core.cache import cache


class BannerView(GenericViewSet, ListModelMixin):
    # 无论有多少条都只按顺序显示配置的条数
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]
    serializer_class = serializers.BannerSerializer

    print(type(queryset))

    # 重写list方法
    def list(self, request, *args, **kwargs):
        # 先去缓存里拿数据，不调用数据库
        banner_list = cache.get('banner_list')
        if not banner_list:
            # 直接调用父类，得到序列化的数据
            response = super().list(request, *args, **kwargs)
            # 再加到缓存，方便下一次同样的访问直接去缓存取
            cache.set('banner_list', response.data, 60 * 60 * 24)
            return response
        return Response(data=banner_list)
